var outputerrfun = function(err){console.log(JSON.stringify(err));console.log(JSON.stringify(err.stack))}

angular.module('starter.controllers', ['ionic', "checklist-model"])

.controller('AppCtrl', function($scope, $state, $window, $ionicModal, $ionicLoading, $ionicPopover, $cordovaSQLite, $timeout, SOAP, DB, USER) {
  // Form data for the login modal
  $scope.loginData = {};
  $scope.userInfo = {};

  // Create the login modal that we will use later
 


  $ionicModal.fromTemplateUrl('templates/login.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.loginModal = modal;
  });

  $ionicModal.fromTemplateUrl('templates/customerinfo.html', {
    scope: $scope
  }).then(function(modal){
    $scope.infoModal = modal;
  })

  $scope.showuserinfo = function(){
    if ($window.localStorage['cusId']) {
      $state.go("app.info", {cusId: $window.localStorage['cusId']},{reload: true})
    } else {
      $state.go("login",{},{})
    }
  }
  // Triggered in the login modal to close it
  $scope.closeLogin = function() {
    $scope.loginModal.hide();
  };

  $scope.closeInfoModal = function(){
    $scope.infoModal.hide();
  }
  // Open login  or customerinfo modal

  $scope.loginOrShowInfo = function(){
    if (USER.userinfo().ccusname){
      $scope.infoModal.show()
    } else {
      $scope.loginModal.show()
    }
  }

  $scope.exit_app = function(){
    console.log("exit")
    ionic.Platform.exitApp();
  }

  // Perform the login action when the user submits the login form
  var loadcustomerinfo = function(cusId){
    $ionicLoading.show({template: '登陆成功,获取个人信息...'})
    SOAP.LoadCustomerInfo(
      function(r){
        console.log(r)
        USER.setuserinfo(JSON.parse(r.getLoadCustomerInfoResult())[0])
        $scope.userInfo = USER.userinfo()
        $ionicLoading.hide()
        $scope.closeLogin()
      },
      function(e){
        console.log(e)
        $ionicLoading.hide()
      }, cusId)
  }
  $scope.doLogin = function() {
    $ionicLoading.show({template: '登录中...'})
    SOAP.CustomerLogin(
      function(r){
        console.log(r)
        $ionicLoading.hide()
        if (r.getCustomerLoginResult() > 0){
          loadcustomerinfo(r.getCustomerLoginResult())  
        } else {
          console.log("invalid username or password")
        }
        
      },
      function(e){
        console.log(e)
        $ionicLoading.hide()
      },
      $scope.loginData.username, $scope.loginData.password
      )
  };
  $scope.logOut = function(){
    USER.setuserinfo({})
    $scope.userInfo = USER.userinfo()
    $scope.infoModal.hide()
  }
})

.controller('PlaylistsCtrl', function($scope) {
  $scope.playlists = [
    { title: 'Reggae', id: 1 },
    { title: 'Chill', id: 2 },
    { title: 'Dubstep', id: 3 },
    { title: 'Indie', id: 4 },
    { title: 'Rap', id: 5 },
    { title: 'Cowbell', id: 6 }
  ];
})

.controller('PlaylistCtrl', function($scope, $stateParams) {
})

.controller('ClassesCtrl', function($scope,$ionicPlatform, $window, $timeout, $ionicLoading, $ionicPopup, $cordovaSQLite, SOAP, DB) {

  $ionicLoading.show({template: '加载科目中...'})
  $ionicPlatform.ready(function(){
    if ($window.localStorage["first"] != 'ok'){
      $ionicLoading.show({template: '首次执行,初始化应用数据...'})
      $timeout(function(){
        $scope.classes = DB.classes();
        $ionicLoading.hide()
      }, 1000 * 35)
      $window.localStorage["first"] = 'ok'
      sqlitePlugin.openDatabase({name: "ttexam.db", createFromLocation: 1}, function(opendb){
        db = opendb
        SOAP.LoadRemoteBaseItemChangeList(function(basechangeres){
          var items = JSON.parse(basechangeres.getLoadRemoteBaseItemChangeListResult())
          $.each(items, function(i, v){
              $cordovaSQLite.execute(db, "select * from sys_serverexchangeitem where id = ?", [v.id]).then(
                function(selectres){
                  if (selectres.rows.length == 1){
                    dbdate = new Date(selectres.rows.item(0).dupdatedate)
                    remotedate = new Date(v.dupdatedate)
                    if (remotedate > dbdate) {
                      console.log("New Update " + JSON.stringify(selectres.rows.item(0)))
                      if (selectres.rows.item(0).citemname == 'course'){
                        SOAP.LoadBaseItemUpdateNewData(function(itemsoapres){
                          DB.updateCourse(JSON.parse(itemsoapres.getLoadBaseItemUpdateNewDataResult()))
                        },outputerr, 'course', '')
                      } else if(selectres.rows.item(0).citemname == 'courseclass'){
                        SOAP.LoadBaseItemUpdateNewData(function(itemsoapres){
                          DB.updateCourseClass(JSON.parse(itemsoapres.getLoadBaseItemUpdateNewDataResult()))
                        },outputerr, 'courseclass', '')
                      } else if (selectres.rows.item(0).citemname == 'coursesubclass'){
                        SOAP.LoadBaseItemUpdateNewData(function(itemsoapres){
                          DB.updateCourseSubclass(JSON.parse(itemsoapres.getLoadBaseItemUpdateNewDataResult()))
                        },outputerr, 'coursesubclass', '')  
                      }
                      DB.updateSysExchangeItem(v);
                    }
                  } else {
                    console.log("no such item " + JSON.stringify(v))
                  }
                },outputerr
                )
            })

        },function(err){$ionicLoading.hide(); $ionicPopup.alert({title: "加载失败,请检查网络"})})
      }, function(err){$ionicLoading.hide(); $ionicPopup.alert({title: "打开数据库失败, 请联系管理员"})})
    } else {
      sqlitePlugin.openDatabase({name: "ttexam.db", createFromLocation: 1}, 
        function(res){
          $ionicLoading.hide()
          console.log(JSON.stringify(res))
          db =res
          $scope.classes = DB.classes()
        }, 
        function(err){
          $ionicLoading.hide()
          console.log(JSON.stringify(err))
        });
    }
  })
})

.controller('ClassCtrl', function($scope, $stateParams, DB) {
  $scope.classname = DB.getclass($stateParams.classid).ccoursecname
  $scope.subclasses = DB.getsubclasses($stateParams.classid)
})

.controller('CoursesCtrl', function($scope, $stateParams,  DB) {
  $scope.subclassname = DB.getsubclass($stateParams.subclassid).csubclassname
  $scope.courses = DB.getcourses($stateParams.subclassid)
})

.controller('HomeCtrl', function($scope, $state, $window, $stateParams,$ionicModal,$ionicLoading,$ionicPopup,$timeout,$cordovaSQLite, DB, SOAP){
  if ($stateParams.currentCourseId){
    $scope.currentCourseId = parseInt($stateParams.currentCourseId)  
  } else {
    if ($window.localStorage['currentcourseid']){
      $scope.currentCourseId = parseInt($window.localStorage['currentcourseid'])
    } else {
      $scope.currentCourseId = 1;
    }
  }
  
  if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
    if (db) {
      $cordovaSQLite.execute(db, "select * from course where icourseid = ?", [$scope.currentCourseId]).then(
        function(res){
          $scope.course = res.rows.item(0)
        },outputerrfun
      );
    }
  } else {
    $scope.course = DB.getcourse($scope.currentCourseId)
  }

  $scope.unlockData = {};
  $scope.show_active_modal = function(){
    if ($scope.active_modal){
      $scope.active_modal.show();
    } else {
      $ionicModal.fromTemplateUrl('templates/active.html', {
        scope: $scope
      }).then(function(modal){
        $scope.active_modal = modal;
        $scope.active_modal.show();
      });
    }
  }
  $scope.close_active_modal = function(){
    if ($scope.active_modal){ $scope.active_modal.hide()}
  }
  $scope.openbuyUrl = function(){window.open("http://shop116271253.taobao.com/", "_system")}
  $scope.unlockCourse = function(){

    if ($scope.course.ihadbuy == 1){
      $ionicPopup.alert({title: '该课程已经激活}'})
      return
    }
    if ($scope.currentCourseId > 0){
      if (!$scope.unlockData.serial) {
        $ionicPopup.alert({title: '激活码不能为空'})
      } else {
        SOAP.RegistSerialCode(function(res){
          if (res.getRegistSerialCodeResult().length == 0) { //success
            $cordovaSQLite.execute(db, "update course set ihadbuy = 1 where icourseid = ?",[$scope.currentCourseId])
            .then(function(update){
              $scope.course.ihadbuy = 1;

              $scope.downloading = $ionicPopup.show({
                  scope: $scope,
                  template: '<i id="downloadSubjectPercent" class="text-center">题库下载中</i>'
                  + '<progress id="downloadSubjectProgress" max={{100}} value="0"></progress>',
                  buttons: [{text: '取消下载', type: 'button-assertive', onTap: function(){console.log("cancle downloading"); cancle = true;}}]
              })
              $scope.downloadInfo = {subject: false, chapter: true}
              $scope.downloadSubject($scope.currentCourseId, 1)  
            },
              function(err){$ionicPopup.alert({title: "更新课程出错, 激活失败"})})
          } else { //fail
            $ionicPopup.alert({title: res.getRegistSerialCodeResult()})
          }
        },function(e){
          $ionicPopup.alert({title: '激活失败 ' + JSON.stringify(e)})
        },$scope.unlockData.serial, $scope.currentCourseId, device.uuid, 0,0)
      }
    } else {
      $ionicPopup.alert({title: "请先选择科目"})
    }
  }
  $scope.downloadSubject = function(courseId, pay){
    SOAP.LoadNewCourseSubject_HadDistrict(
      function(res){
        var subIds = JSON.parse(res.getLoadNewCourseSubject_HadDistrictResult()).map(function(v){return v.isubjectid}).join(',')
        SOAP.LoadCourseSubjectListInfo(
          function(res2){
            var subjects = JSON.parse(res2.getLoadCourseSubjectListInfoResult())
            $scope.downloadSbujectInfo = {downloadSubjectCount: 0,  totalSubjectCount: subjects.length}
            $('#downloadSubjectProgress').attr("max", subjects.length)
            $.each(subjects,function(i,vv){
              if ($cordovaSQLite){
                if (vv.bpicquestion == "TRUE"){
                  console.log("loaing pic")
                  console.log(JSON.stringify(vv))
                  SOAP.LoadSubjectImageList(function(picres){
                    console.log("got pic")
                    $.each(JSON.parse(picres.getLoadSubjectImageListResult()), function(_i, _v){
                      console.log("update pic")
                      $cordovaSQLite.execute(db, "select * from sys_tableimage where csourceid = ? and ctblname = ?", [vv.isubjectid, _v.ctblname])
                      .then(function(sqlres){
                        if (sqlres.rows.length == 0){//insert
                          $cordovaSQLite.execute(db, "insert into sys_tableimage (ctblname, csourceid, pimage, cextname) values (?, ?, ?,?)",[_v.ctblname, vv.isubjectid, _v.pimage, _v.cextname])
                          .then(function(ok1){
                            console.log(JSON.stringify(ok1))
                          }, function(err1){
                            console.log(JSON.stringify(err1))
                          })
                        } else {//update
                          $cordovaSQLite.execute(db, "update sys_tableimage set ctblname = ? , csourceid = ?, pimage = ? , cextname = ?",[_v.ctblname, vv.isubjectid, _v.pimage, _v.cextname])
                          .then(function(ok1){
                            console.log(JSON.stringify(ok1))
                          }, function(err1){
                            console.log(JSON.stringify(err1))
                          })
                        }
                      },function(sqlerr){console.log(JSON.stringify(sqlerr))})    
                    })
                  }, function(loderr){JSON.stringify(loderr)}, vv.isubjectid)
                }
                
                $cordovaSQLite.execute(db, "insert into  coursesubject (bpicanswer, bpicquestion,brich, bstopflag, canswer, cdescription, " +
                  "cmaker, cquestion, csubjecttype, ctitle, dchangedate, ianswercount, ichapterid, ichaptertype," +
                  "icourseid, iindex, iscore, isubjectid, isubjecttype) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                  [vv.bpicanswer, vv.bpicquestion, vv.brich, vv.bstopflag, vv.canswer, vv.cdescription, vv.cmaker, vv.cquestion, 
                   vv.csubjecttype, vv.ctitle, vv.dchangedate, vv.ianswercount, vv.ichapterid, vv.ichaptertype,
                   vv.icourseid, vv.iindex, vv.iscore, vv.isubjectid, vv.isubjecttype]).then(
                  function(res){
                    $scope.downloadSbujectInfo.downloadSubjectCount++
                    var text = "题目内容下载中" + parseInt($scope.downloadSbujectInfo.downloadSubjectCount/$scope.downloadSbujectInfo.totalSubjectCount * 100) + '%'
                    
                    $('#downloadSubjectPercent').text(text)
                    $('#downloadSubjectProgress').attr("value", $scope.downloadSbujectInfo.downloadSubjectCount)
                    if (i >= $scope.downloadSbujectInfo.totalSubjectCount - 1){
                      $scope.downloadnotify("subject")
                    }
                    // console.log("insert done")
                  },function(res){
                    $scope.downloadSbujectInfo.downloadSubjectCount++
                    var text = "题目内容下载中" + parseInt($scope.downloadSbujectInfo.downloadSubjectCount/$scope.downloadSbujectInfo.totalSubjectCount * 100) + '%'
                    
                    $('#downloadSubjectPercent').text(text)
                    $('#downloadSubjectProgress').attr("value", $scope.downloadSbujectInfo.downloadSubjectCount)
                    if (i >= $scope.downloadSbujectInfo.totalSubjectCount - 1){
                      $scope.downloadnotify("subject")
                    }
                    // console.log("insert error")
                  }
                  )
              }
            })
          },outputerrfun, courseId, subIds);
      },outputerrfun, courseId, pay, "", '2000-01-01');
  }
  $scope.show_correct_page = function(){
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
      $cordovaSQLite.execute(db, "select * from coursechapter where icourseid = ? and igrade = 0", [$scope.currentCourseId]).then(
        function(res){
          if (res.rows.length == 0){
            $scope.show_choose_modal()
          } else {
            var redirect = '#/correct/' + $scope.currentCourseId
            console.log("redirect to " + redirect)
            window.location.href = redirect
          }
        },outputerrfun)
    } else {
     var redirect = '#/correct/' + $scope.currentCourseId
      console.log("redirect to " + redirect)
      window.location.replace(redirect)
    }
  }
  $scope.show_collect_page =  function(){
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){    
      $cordovaSQLite.execute(db, "select * from coursechapter where icourseid = ? and igrade =0", [$scope.currentCourseId]).then(
        function(res){
          if (res.rows.length == 0){
            $scope.show_choose_modal()
          } else {
            var redirect = '#/collect/' + $scope.currentCourseId
            console.log("redirect to " + redirect)
            window.location.href = redirect
          }
        },outputerrfun)
    } else {
     var redirect = '#/collect/' + $scope.currentCourseId
      console.log("redirect to " + redirect)
      window.location.href = redirect        
    }
  }
  $scope.show_simulation_modal = function(){
    if ($scope.course.ihadbuy != 1){
      $ionicPopup.alert({title: "需要激活才能进行模拟考试"})
    } else {
      $state.go("simulation", {courseId: $scope.course.icourseid}, {reload: true})
    }
  }
  $scope.downloadStep = {}
  $scope.downloadnotify = function(dtype){
    console.log(dtype)
    console.log(JSON.stringify($scope.downloadStep))
    console.log(JSON.stringify($scope.downloading))
    if (dtype == "chapter"){
      $scope.downloadStep.chapter = true
    }
    if (dtype == "subject"){
      $scope.downloadStep.subject = true
      $timeout(function(){$scope.downloading.close()}, 1000 * 5)
    }
    if ($scope.downloadStep.subject && $scope.downloadStep.chapter){
      $scope.downloading.close()
    }
  }
  $scope.show_choose_modal = function(){
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
      $cordovaSQLite.execute(db, "select * from coursechapter where icourseid = ? and igrade = 0", [$scope.currentCourseId]).then(
      function(res){
        console.log(JSON.stringify(res))
        $scope.chapters = []
        for (var i = 0; i < res.rows.length; ++i){
          $scope.chapters.push(res.rows.item(i));
        }
        if ($scope.chapters.length  == 0){ //需要下载课程
          $ionicLoading.show({template: '查询最新章节数据...'});
          SOAP.LoadNewCourseChapter_HadDistrice( //章节数量
            function(r){
              if (r.getLoadNewCourseChapter_HadDistriceResult() == ""){
                $ionicLoading.hide()
                $ionicPopup.alert({title: "没有章节数据"})
                return
              }
              $scope.newChapters = JSON.parse(r.getLoadNewCourseChapter_HadDistriceResult());
              $scope.downloadInfo = {totalChapterCount: $scope.newChapters.length, downloadChapterCount: 0}
              $ionicLoading.hide();
              var confirmDownload = $ionicPopup.confirm({
                template: '<p class="text-center">确认下载课程吗,非WIFI状态下会消耗流量</p>',
                cancleType: 'button-assertive',cancelText: '暂不下载', okType: 'button-positive', okText: '确认下载'
              })
            confirmDownload.then(function(confirm){
              if (confirm){
                var cancle = false;
                $scope.downloading = $ionicPopup.show({
                  scope: $scope,
                  template: '<i id="downloadPercent" class="text-center">章节内容下载中</i>'
                  + '<progress id="downloadProgress" max={{downloadInfo.totalChapterCount}} value="downloadInfo.downloadChapterCount"></progress>'
                  + '<i id="downloadSubjectPercent" class="text-center">题库下载中</i>'
                  + '<progress id="downloadSubjectProgress" max={{100}} value="0"></progress>',
                  buttons: [{text: '取消下载', type: 'button-assertive', onTap: function(){console.log("cancle downloading"); cancle = true;}}]
                })
                $scope.downloadSubject($scope.currentCourseId, 0);
                $.each($scope.newChapters, function(index, value){
                  SOAP.LoadCourseChapterInfo(
                    function(res){
                      
                      var cs = JSON.parse(res.getLoadCourseChapterInfoResult())[0]
                      $cordovaSQLite.execute(db, "select * from coursechapter where ichapterid = ?", [cs.ichapterid]).then(
                        function(res){
                          //console.log("select " + JSON.stringify(res))
                          if (res.rows.length == 0){
                            $cordovaSQLite.execute(db, "insert into coursechapter " + 
                              "(ballowtest, bendgrade, bstopflag, cchaptercode, cchaptername, cdcname, cmemo, dchangedate, " + 
                              "ichapterid,icount, icourseid, iexamtime, igrade, itype, bdownload ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                              [cs.ballowtest, cs.bendgrade, cs.bstopflag, cs.cchaptercode, cs.cchaptername, cs.cdcname, cs.cmemo, cs.dchangedate, cs.ichapterid, cs.icount, cs.icourseid, cs.iexamtime, cs.igrade, cs.itype,1]).then(
                              function(res){
                                //console.log("result" + JSON.stringify(res))},function(res){"error" + console.log(JSON.stringify(res))
                              })
                          } else {
                            $cordovaSQLite.execute(db, "update coursechapter set ballowtest = ?, bendgrade = ?, bstopflag = ?, cchaptercode = ?," +
                              "cchaptername = ?, cdcname = ?, cmemo = ?, dchangedate = ?, ichapterid = ?, icount = ?," +
                              "icourseid = ?, iexamtime = ?, igrade = ?, itype = ? , bdownload = ? where ichapterid = ?",
                              [cs.ballowtest, cs.bendgrade, cs.bstopflag, cs.cchaptercode, cs.cchaptername, cs.cdcname, cs.cmemo, cs.dchangedate, cs.ichapterid, cs.icount, cs.icourseid, cs.iexamtime, cs.igrade, cs.itype,cs.ichapterid],1).then(
                              function(res){
                                //console.log("result" + JSON.stringify(res))},function(res){"error" + console.log(JSON.stringify(res))
                              })
                          }
                          $scope.downloadInfo.downloadChapterCount++
                          var text = "章节内容下载中" + parseInt($scope.downloadInfo.downloadChapterCount/$scope.downloadInfo.totalChapterCount * 100) + '%'
                          $('#downloadPercent').text(text)
                          $('#downloadProgress').val($scope.downloadInfo.downloadChapterCount)
                          if ($scope.downloadInfo.downloadChapterCount == $scope.downloadInfo.totalChapterCount) {
                            console.log("chapter downloading complete!!!")
                            $scope.downloadnotify("chapter")
                            //downloading.close()
                          }
                        },
                        function(err){
                          console.log("select err" + JSON.stringify(res))
                        }
                      );
                    },
                    function(err){
                      console.log("error while downloading chapter")
                    }, value.ichapterid
                    );
                })
                // downloading.then(function(){console.log("popup closed")})
              } else {
                console.log("cancle");
              }
            })
          },
          function(err){console.log(JSON.stringify(err));$ionicLoading.hide()},
          $scope.currentCourseId, 0, '', '2000-01-01'
          );
        } else {
          var redirect = '#/choose_chapter/' + $scope.currentCourseId
          console.log("redirect to " + redirect)
          window.location.href = redirect
        }
      },function(err){
        //$ionicLoading.hide()
        $ionicPopup.alert({title: "加载失败,请稍后重试"})
      }); //select chapters
    } else {
      var redirect = '#/choose_chapter/' + $scope.currentCourseId
      console.log("redirect to " + redirect)
      window.location.href = redirect
    }
  }
})

.controller("CorrectCtrl", function($scope, $stateParams, $cordovaSQLite){
  $scope.chapters = [], $scope.list_url = "correctlist", $scope.url_name ="错题重做"
  if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
    $cordovaSQLite.execute(db, "select c.ichapterid, c.cchaptername, count(s.bcorrect) as total_wrong " +
     "from coursechapter c, coursesubject s " + 
     " where c.ichapterid = s.ichapterid and c.icourseid = ? and s.bcorrect = ? group by c.icourseid", [$stateParams.courseId, false]).then(
      function(res){
        for (var i = 0; i < res.rows.length; ++i){
          $scope.chapters.push(res.rows.item(i))
        }
      },outputerrfun)
  } else {
    for (var i = 0; i < 10; ++i){
      $scope.chapters.push({ichapterid: i, cchaptername: 'correct name ' + i, total_wrong: i})
    }
  }
})
.controller("CorrectListCtrl", function($scope, $stateParams, $cordovaSQLite){
  $scope.subjects = []
  if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
    $cordovaSQLite.execute(db, "select * from coursesubject where ichapterid = ? and bcorrect = ?", [$stateParams.chapterId, false]).then(
      function(res){
        for (var i = 0; i < res.rows.length; ++i){
          $scope.subjects.push(res.rows.item(i))
        }
      },outputerrfun)
  } else {
    for (var i = 0; i < 10; ++i){
      $scope.subjects.push({cquestion: "correct I'm the question " + i, iindex: i})
    }
  }
  $scope.start_practice = function(index){
    window.location.href = "#/practice/" + $stateParams.chapterId + "/1/0/" + index
  }
})
.controller('CollectCtrl', function($scope, $stateParams, $cordovaSQLite){
  $scope.chapters = [], $scope.list_url = "collectlist", $scope.url_name ="我的收藏"
  if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
    $cordovaSQLite.execute(db, "select c.ichapterid, c.cchaptername, count(s.bcollect) as total_wrong " +
     "from coursechapter c, coursesubject s " + 
     " where c.ichapterid = s.ichapterid and c.icourseid = ? and s.bcollect = ? group by c.icourseid", [$stateParams.courseId, true]).then(
      function(res){
        for (var i = 0; i < res.rows.length; ++i){
          $scope.chapters.push(res.rows.item(i))
        }
      },outputerrfun)
  } else {
    for (var i = 0; i < 10; ++i){
      $scope.chapters.push({ichapterid: i, cchaptername: 'collect name ' + i, total_wrong: i})
    }
  }
})
.controller("CollectListCtrl", function($scope, $stateParams, $cordovaSQLite){
  console.log(JSON.stringify($stateParams))
  $scope.subjects = []
  if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
    $cordovaSQLite.execute(db, "select * from coursesubject where ichapterid = ? and bcollect = ?", [$stateParams.chapterId, true]).then(
      function(res){
        for (var i = 0; i < res.rows.length; ++i){
          $scope.subjects.push(res.rows.item(i))
        }
      },outputerrfun)
  } else {
    for (var i = 0; i < 10; ++i){
      $scope.subjects.push({cquestion: "collect I'm the question " + i, iindex: i})
    }
  }
  $scope.start_practice = function(index){
    window.location.href = "#/practice/" + $stateParams.chapterId + "/0/1/" + index
  }
})
.controller('ChooseChapterCtrl', function($scope, $stateParams,$ionicLoading, $ionicModal, $ionicPopup, $cordovaSQLite,DB){
  $scope.course = {},$scope.chapter = {}, $scope.chapters = [];
  console.log(JSON.stringify($stateParams))
  if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
    $cordovaSQLite.execute(db, "select * from course where icourseid = ?", [$stateParams.courseId]).then(
      function(res){
        $scope.course = res.rows.item(0);
        console.log(JSON.stringify($scope.course))
        $scope.pch = {cchaptername: "章节练习", icourseid: $stateParams.courseId, ichapterid: 'pch'}
        $cordovaSQLite.execute(db, "select count(s.bcorrect) as totalcount from coursesubject s, coursechapter c where s.ichapterid = c.ichapterid and s.bcorrect = 'true' and c.itype = 0 and c.icourseid = ?", [$scope.course.icourseid])
        .then(function(res){
          $scope.pch.correcttotal = parseInt(res.rows.item(0).totalcount)
        },outputerrfun);
        $cordovaSQLite.execute(db, "select count(s.bcorrect) as totalcount from coursesubject s, coursechapter c where s.ichapterid = c.ichapterid and s.bcorrect = 'false' and c.itype = 0 and c.icourseid = ?", [$scope.course.icourseid])
        .then(function(res){
          $scope.pch.wrongtotal = parseInt(res.rows.item(0).totalcount)
        },outputerrfun)
        $cordovaSQLite.execute(db, "select count(1) as totalcount from coursesubject s, coursechapter c where s.ichapterid = c.ichapterid and c.itype = 0 and c.icourseid = ?", [$scope.course.icourseid])
        .then(function(pchres){
          $scope.pch.icount = parseInt(pchres.rows.item(0).totalcount)
        },outputerrfun)
        $cordovaSQLite.execute(db, "select * from coursechapter where itype = 1 and icourseid = ? and igrade = 0", [$scope.course.icourseid]).then(
          function(res2){
            $scope.chapters = [];
            for (var i = 0; i < res2.rows.length; ++i){
              $scope.chapters.push(res2.rows.item(i))
            }
            $.each($scope.chapters, function(i,v){
              v.correcttotal = 0, v.wrongtotal = 0;
              $cordovaSQLite.execute(db, "select count(s.bcorrect) as totalcount from coursesubject s, coursechapter c where s.ichapterid = c.ichapterid and c.itype = 1 and s.bcorrect = 'true' and c.cchaptercode like ?",
                [v.cchaptercode + '%'])
              .then(function(correctres){
                  v.correcttotal  = parseInt(correctres.rows.item(0).totalcount)
              },outputerrfun)
              $cordovaSQLite.execute(db, "select count(s.bcorrect) as totalcount from coursesubject s, coursechapter c where s.ichapterid = c.ichapterid and c.itype = 1 and s.bcorrect = 'false' and c.cchaptercode like ?",
                [v.cchaptercode + '%'])
              .then(function(wrongres){
                  v.wrongtotal  = parseInt(wrongres.rows.item(0).totalcount)     
              },outputerrfun)
              $cordovaSQLite.execute(db, "select count(1) as totalcount from coursesubject s, coursechapter c where s.ichapterid = c.ichapterid and c.itype = 1 and c.cchaptercode like ?",
                [v.cchaptercode + '%'])
              .then(function(chres){
                v.icount = parseInt(chres.rows.item(0).totalcount)
              })
            })
            console.log(JSON.stringify($scope.chapters))
          },outputerrfun
        );
      },outputerrfun
    );
  } else {
    $scope.chapters = DB.getsubchapters(parseInt($stateParams.courseId))
    $scope.course = DB.getcourse(parseInt($stateParams.courseId))
  }
  $scope.select_sub_chapter = function(chapter){
    console.log(JSON.stringify(chapter))
    window.location.href = "#/choose_subchapter/" + chapter.icourseid + "/" + chapter.ichapterid
    // console.log(JSON.stringify(chapter))
    // if (chapter.bendgrade == 'FALSE'){
    //   $scope.chapter = chapter, $scope.chapters = [];
    //   $ionicLoading.show({template: '加载中...'})
    //   if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
    //     $cordovaSQLite.execute(db, "select * from coursechapter where icourseid = ? and igrade = ? and cchaptercode like ?", [chapter.icourseid, chapter.igrade + 1, chapter.cchaptercode + '%']).then(
    //       function(res){
    //         for (var i = 0; i < res.rows.length; ++i){
    //           $scope.chapters.push(res.rows.item(i))
    //         }
    //         $ionicLoading.hide()
    //       }
    //     );
    //   } else {
    //     $scope.chapters = DB.getsubchapters(chapter)
    //     $ionicLoading.hide()
    //   }
    // } else {
    //   if (chapter.ballowtest == "TRUE" || $scope.course.ihadbuy == 1){
    //     window.location.href = '#/practice/' + chapter.ichapterid + '/0/0/0'
    //   } else {
    //     $ionicPopup.confirm({
    //       template: '<p class="text-center">需要激活才能查看题目</p>',
    //       cancleType: 'button-positive',cancelText: '取消', okType: 'button-positive', okText: '确认'
    //     })
    //   }
    // }
  }

})

.controller('ChooseSubChapterCtrl', function($scope, $window,$ionicModal, $ionicLoading, $ionicPopup, $stateParams,$timeout, $cordovaSQLite, DB){
  $scope.course = {},$scope.chapter = {}, $scope.chapters = [];
  console.log(JSON.stringify($stateParams))
  if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
    if ($stateParams.chapterId == 'pch'){
      $scope.chapter = {cchaptername: "章节练习"}
      $cordovaSQLite.execute(db, "select * from coursechapter where icourseid = ? and itype = 0 and igrade = 0", [$stateParams.courseId])
      .then(
        function(res2){
          $scope.chapters = [];
          for (var i = 0; i < res2.rows.length; ++i){
            $scope.chapters.push(res2.rows.item(i))
          }
          $.each($scope.chapters, function(i,v){
            v.correcttotal = 0, v.wrongtotal = 0;
            $cordovaSQLite.execute(db, "select count(s.bcorrect) as totalcount from coursesubject s, coursechapter c where s.ichapterid = c.ichapterid and c.itype = 0 and s.bcorrect = 'true' and c.cchaptercode like ?",
              [v.cchaptercode + '%'])
            .then(function(correctres){
                v.correcttotal  =  parseInt(correctres.rows.item(0).totalcount)
            },outputerrfun)
            $cordovaSQLite.execute(db, "select count(s.bcorrect) as totalcount from coursesubject s, coursechapter c where s.ichapterid = c.ichapterid and c.itype = 0 and s.bcorrect = 'false' and c.cchaptercode like ?",
              [v.cchaptercode + '%'])
            .then(function(wrongres){
                v.wrongtotal  = parseInt(wrongres.rows.item(0).totalcount)             
            },outputerrfun)
            $cordovaSQLite.execute(db,  "select count(1) as totalcount from coursesubject s, coursechapter c where s.ichapterid = c.ichapterid and c.itype = 0 and c.cchaptercode like ?",
              [v.cchaptercode + '%'])
            .then(function(pchres){
              v.icount = parseInt(pchres.rows.item(0).totalcount)
            },outputerrfun)
          })
          console.log(JSON.stringify($scope.chapters))
        },outputerrfun);
    } else {

      $cordovaSQLite.execute(db, "select * from coursechapter where ichapterid = ?", [$stateParams.chapterId])
      .then(function(reschapter){
        $scope.chapter = reschapter.rows.item(0);
        $cordovaSQLite.execute(db, "select * from coursechapter where itype = ? and icourseid = ? and igrade = ? and cchaptercode like ?", 
          [$scope.chapter.itype, $scope.chapter.icourseid, $scope.chapter.igrade + 1, $scope.chapter.cchaptercode + '%'])
        .then(
          function(res2){
            $scope.chapters = [];
            for (var i = 0; i < res2.rows.length; ++i){
              $scope.chapters.push(res2.rows.item(i))
            }
            $.each($scope.chapters, function(i,v){
              v.correcttotal = 0, v.wrongtotal = 0;
              $cordovaSQLite.execute(db, "select count(s.bcorrect) as totalcount from coursesubject s, coursechapter c where s.ichapterid = c.ichapterid and c.itype = ? and s.bcorrect = 'true' and c.cchaptercode like ?",
                [v.itype, v.cchaptercode + '%'])
              .then(function(correctres){
                  v.correcttotal  = parseInt(correctres.rows.item(0).totalcount)
              },outputerrfun)
              $cordovaSQLite.execute(db, "select count(s.bcorrect) as totalcount from coursesubject s, coursechapter c where s.ichapterid = c.ichapterid and c.itype = ? and s.bcorrect = 'false' and c.cchaptercode like ?",
                [v.itype, v.cchaptercode + '%'])
              .then(function(wrongres){
                  v.wrongtotal  = parseInt(wrongres.rows.item(0).totalcount)            
              },outputerrfun)
              $cordovaSQLite.execute(db, "select count(1) as totalcount from coursesubject s, coursechapter c where s.ichapterid = c.ichapterid and c.itype = ? and c.cchaptercode like ?",
                [v.itype, v.cchaptercode + '%'])
              .then(function(countres){
                v.icount = parseInt(countres.rows.item(0).totalcount)
              })
            })
            console.log(JSON.stringify($scope.chapters))
          },outputerrfun);
      },outputerrfun)
    }
    $cordovaSQLite.execute(db, "select * from course where icourseid = ?", [$stateParams.courseId])
    .then(
      function(res){
        $scope.course = res.rows.item(0);
        console.log(JSON.stringify($scope.course))
      },outputerrfun);
  } else {
    $scope.chapter = DB.getchapter(parseInt($stateParams.chapterId))
    $scope.chapters = DB.getsubchapters($scope.chapter)
    $scope.course = DB.getcourse($scope.chapter.icourseid)
  }

  $scope.choose_subchapter = function(chapter){
    if (chapter.bendgrade == 'FALSE'){
      $window.localStorage['currentcourseid'] = $stateParams.courseId
      window.location.href = "#/choose_subchapter/" + $stateParams.courseId + "/" + chapter.ichapterid
    } else {
      if (chapter.ballowtest == "TRUE" || $scope.course.ihadbuy == 1){
        window.location.href = '#/practice/' + chapter.ichapterid + '/0/0/0'
      } else {
        $ionicLoading.show({template: "需要激活才能查看题目"})
        $timeout(function(){$ionicLoading.hide()}, 800)
      }
    }
  }

})

.controller('PracticeCtrl', function($scope, $window, $stateParams, $ionicLoading, $ionicModal, $cordovaSQLite, SOAP, DB){
  if ($window.localStorage['setting']){
    $scope.setting = JSON.parse($window.localStorage['setting'])
  } else {
    $scope.setting = {selectfont : {class: 'h3', name: '大号'}}
  }
  console.log(JSON.stringify($scope.setting))
  console.log($scope.setting.selectfont.class)

  console.log(JSON.stringify($stateParams))
  $scope.answerset = ['A','B','C','D','E','F','G']
  $scope.datas = [{title: 'question1'},{title: 'question12'}]
  var query = "select * from coursesubject where ichapterid = ?"
  var params = [$stateParams.chapterId]
  if ($stateParams.correct == 1) {
    query = query + " and bcorrect = ?"
    params.push(false)
  }
  if ($stateParams.collect == 1){
    query = query + 'and bcollect = ?'
    params.push(true)
  }
  if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
    $ionicLoading.show({template: '加载试题中...'})
    $cordovaSQLite.execute(db, "select * from coursechapter where ichapterid = ?", [$stateParams.chapterId])
    .then(function(res){
      $scope.coursechapter = res.rows.item(0)
    },outputerrfun)
    $cordovaSQLite.execute(db, query, params).then(
      function(res){
        $scope.subjects = []
        for (var i = 0; i < res.rows.length; ++i){
          var item = res.rows.item(i)
          item.iindex = i+1
          item.answerset = $scope.answerset.slice(0, item.ianswercount)
          if (item.isubjecttype == 0){
            item.single = true;
          } else {
            item.single = false;
            if(item.cmyanswer){
              item.myanswer_multi = item.cmyanswer.split('')
            } else {
              item.myanswer_multi = []
            }
          }
          if (item.cmyanswer){
            item.show_desc = true
          }
          if (item.bcollect == 'true') {
            item.src = "img/collect1.png"
          } else {
            item.src = "img/collect0.png"
          }
          $scope.subjects.push(item)
        }
        $.each($scope.subjects, function(i, findpicv){
          if (findpicv.bpicquestion == "TRUE") {
            $cordovaSQLite.execute(db, "select * from sys_tableimage where csourceid = ? ",[findpicv.isubjectid])
            .then(function(picres){
              findpicv.pictrues = []
              for (var j = 0; j <  picres.rows.length; ++j){
                findpicv.pictrues.push('<img src="data:image/jpg;base64,' + picres.rows.item(j).pimage + '"/>')
              }
              findpicv.ctitle = findpicv.ctitle.replace('{图}', findpicv.pictrues[0])
              findpicv.cquestion = findpicv.cquestion.replace('{图}', findpicv.pictrues[0])
              for (var jj = 0; jj < picres.rows.length; ++jj){
                findpicv.ctitle = findpicv.ctitle.replace('{图' + jj + '}', findpicv.pictrues[jj])
                findpicv.cquestion = findpicv.cquestion.replace('{图' + jj + '}', findpicv.pictrues[jj])
              }
            },outputerrfun)
          }
        })
        console.log(res.rows.length)
        $ionicLoading.hide()
        $scope.currentIndex = 0;
        $scope.subject = $scope.subjects[0];
        if (parseInt($stateParams.indexId) > 0) {
          $.each($scope.subjects, function(i, v){
            if (v.iindex == parseInt($stateParams.indexId)){
              $scope.currentIndex = i;
              $scope.subject = $scope.subjects[i];
            }
          })
        }
      },outputerrfun);//execute
  } else {
    $scope.coursechapter = DB.getchapter(48)
    $scope.subjects = []
    for (var i = 0; i < 200; ++i){
      if (i % 3 == 0){
        $scope.subjects.push({isubjectid: i,iindex: i, iscore: i, ctitle: '标题' + i, cdescription: '描述' + i,
         canswer: 'A', answerset: $scope.answerset.slice(0,4), isubjecttype: 0, csubjecttype: "单选"}) 
      } else if (i % 3 == 1){
        var picsrc = '<img src="" />'        
        var title = '标题{图}' + i 
        title = title.replace('{图}' , picsrc)
        $scope.subjects.push({iindex: i, iscore: i, ctitle: title,
         cdescription: '描述' + i, canswer: 'ABC', answerset: $scope.answerset.slice(0,5), isubjecttype: 1, csubjecttype: "多选",
         myanswer_multi: [], bpicquestion: "TRUE",  src: "img/collect0.png",
         pictrues: []
       })
        // $scope.subjects[$scope.subjects.length - 1].ctitle.replace('{图}', picsrc) 
      } else {
         $scope.subjects.push({iindex: i, iscore: i, ctitle: '标题' + i,cdescription: '描述' + i, cmyanswer: '', canswer: '对', answerset: $scope.answerset.slice(0,5), isubjecttype: 2, csubjecttype: "判断"})
      }
    }
    $scope.currentIndex = 0;
    $scope.subject = $scope.subjects[0];
    if (parseInt($stateParams.indexId) > 0) {
      $.each($scope.subjects, function(i, v){
        if (v.iindex == parseInt($stateParams.indexId)){
          $scope.currentIndex = i;
          $scope.subject = $scope.subjects[i];
        }
      })
    }
  }
  $scope.next_subject = function(){
    if ($scope.currentIndex < $scope.subjects.length - 1){
      $scope.currentIndex++
      $scope.subject = $scope.subjects[$scope.currentIndex]
    } else {
      $scope.currentIndex=0
      $scope.subject = $scope.subjects[$scope.currentIndex]
    }
  }
  $scope.pre_subject = function(){
    if ($scope.currentIndex > 0){
      $scope.currentIndex--
      $scope.subject = $scope.subjects[$scope.currentIndex]
    } else {
      $scope.currentIndex = $scope.subjects.length - 1
      $scope.subject = $scope.subjects[$scope.currentIndex]
    }
  }
  $scope.retry_question = function(){
    $scope.subject.cmyanswer = ''
    $scope.subject.myanswer_single = false
    $scope.subject.myanswer_multi = []
    $scope.subject.show_desc = false
  }
  $scope.user_choose_answer_single = function(){
    console.log(JSON.stringify($scope.subject))
    $scope.subject.show_desc = true;
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
      if ($scope.subject.cmyanswer == $scope.subject.canswer){
        $scope.subject.bcorrect = 'true';
        $cordovaSQLite.execute(db, 'update coursesubject set bcorrect = ?,cmyanswer = ? where isubjectid = ?', [$scope.subject.bcorrect, $scope.subject.cmyanswer, $scope.subject.isubjectid])
      } else {
        $scope.subject.bcorrect = 'false';
        $cordovaSQLite.execute(db, 'update coursesubject set bcorrect = ?,cmyanswer = ? where isubjectid = ?', [$scope.subject.bcorrect, $scope.subject.cmyanswer, $scope.subject.isubjectid])
      }
    } else {
      $scope.subject.bcorrect = $scope.subject.cmyanswer == $scope.subject.canswer ? 'true' : 'false';
      console.log($scope.subject.cmyanswer)
    }
  }
  $scope.user_choose_answer_multi = function(){
    console.log(JSON.stringify($scope.subject.myanswer_multi))
  }


  $scope.user_choose_judge = function(answer){
    $scope.subject.cmyanswer = answer
    $scope.subject.show_desc = true;
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
      if ($scope.subject.cmyanswer == $scope.subject.canswer){
        $scope.subject.bcorrect = 'true';
        $cordovaSQLite.execute(db, 'update coursesubject set bcorrect = ?,cmyanswer = ? where isubjectid = ?', [$scope.subject.bcorrect, $scope.subject.cmyanswer, $scope.subject.isubjectid])
        .then(function(res){
          console.log("right select")
          console.log(JSON.stringify(res))
        },
        function(err){
          console.log("right select")
          console.log(JSON.stringify(err))
        })
      } else {
        $scope.subject.bcorrect = 'false'
        $cordovaSQLite.execute(db, 'update coursesubject set bcorrect = ?,cmyanswer = ? where isubjectid = ?',[$scope.subject.bcorrect, $scope.subject.cmyanswer, $scope.subject.isubjectid])
        .then(function(res){
          console.log("wrong select")
          console.log(JSON.stringify(res))
        },
        function(err){
          console.log("wrong select")
          console.log(JSON.stringify(err))
        })
      }
    } else {
      $scope.subject.bcorrect = $scope.subject.cmyanswer == $scope.subject.canswer ? 'true' : 'false';
      console.log($scope.subject.cmyanswer)
    }

  }

  $scope.multi_question_confirm = function(){
    $scope.subject.show_desc = true;
    $scope.subject.cmyanswer = $scope.subject.myanswer_multi.sort().join('')
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
      if ($scope.subject.cmyanswer == $scope.subject.canswer){
        $scope.subject.bcorrect = 'true';
        $cordovaSQLite.execute(db, 'update coursesubject set cmyanswer = ?, bcorrect = ? where isubjectid = ?', [$scope.subject.cmyanswer, $scope.subject.bcorrect, $scope.subject.isubjectid])
      } else {
        $scope.subject.bcorrect = 'false';
        $cordovaSQLite.execute(db, 'update coursesubject set cmyanswer = ?, bcorrect = ? where isubjectid = ?', [$scope.subject.cmyanswer, $scope.subject.bcorrect, $scope.subject.isubjectid])
      }
    } else {
     $scope.subject.bcorrect = $scope.subject.cmyanswer == $scope.subject.canswer ? 'true' : 'false';
      console.log(JSON.stringify($scope.subject.myanswer_multi))
    }
  }
  $scope.show_check_board = function(){
    $scope.groupSubjects = [];
    var groups = $scope.subjects.length / 7 + ($scope.subjects.length % 7 > 0 ? 1 : 0)
    for (var i = 0; i < groups; ++i){
      $scope.groupSubjects.push( $scope.subjects.slice(i*7, (i+1)*7) )
    }
    if ($scope.check_board){
      $scope.check_board.show();
    } else {
      $ionicModal.fromTemplateUrl('templates/modal/check_board.html', {
        scope: $scope
      }).then(function(modal){
        $scope.check_board = modal;
        $scope.check_board.show();
      });
    }
  }

  $scope.select_subject_from_board = function(s){
    $scope.submitsubject = false
    if ($scope.check_board){
      $scope.check_board.hide()
    }
    $scope.subject = s
    $scope.currentIndex = $scope.subjects.indexOf(s)
  }
  $scope.collect_subject = function(){ //收藏试题
    if ($scope.subject.bcollect == 'true') {
      $scope.subject.bcollect = 'false'
    } else {
      $scope.subject.bcollect = 'true'
    }
    if ($scope.subject.bcollect == 'true') {
      $scope.subject.src = "img/collect1.png"
    } else {
      $scope.subject.src = "img/collect0.png"
    }
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
      $cordovaSQLite.execute(db, "update coursesubject set bcollect = ? where isubjectid = ?", [$scope.subject.bcollect,$scope.subject.isubjectid])
    } else {
      console.log($scope.subject.bcollect)
    }
  }
  $scope.redoSubject = function(){
    $ionicLoading.show({template: '清空数据...'})
    $.each($scope.subjects, function(index, value){
      value.cmyanswer = null, value.bcorrect = null, value.show_desc = false, value.myanswer_multi = []
    })
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
      $cordovaSQLite.execute(db, "update coursesubject set cmyanswer = null, bcorrect = null where ichapterid = ?", [$stateParams.chapterId]).then(
        function(res){$ionicLoading.hide()},function(err){$ionicLoading.hide()});
    } else {
      $ionicLoading.hide();
    }
    if ($scope.check_board){$scope.check_board.hide()}
  }
  $scope.calcResult = function(){
    var result = {totalAnswer: 0, rightPercent: 0, rightCount: 0,}
    $.each($scope.subjects, function(index,value){
      if (value.cmyanswer){ result.totalAnswer++ }
      if (value.bcorrect) { result.rightCount++ }
    })
    result.rightPercent = parseInt ( result.rightCount / $scope.subjects.length * 100)
    $scope.result = result;
    $scope.submitsubject = true
  }
  $scope.correct_subject = function(){
    navigator.app.backHistory()
  }

  console.log('subject ' + JSON.stringify($scope.subject))
  $scope.loadnote = function(){
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
      $cordovaSQLite.execute(db, "select * from cs_writenote where isubjectid = ?", [$scope.subject.isubjectid])
      .then(function(res){
        if (res.rows.length == 1){
          $scope.subject.note = res.rows.item(0)
        }
      },outputerrfun)
    } else {
      $scope.subject.note = {cnotetext : '这个题目怎么办', dchangedate: '2015-01-01 08:00'}
    }
    console.log('subject ' + JSON.stringify($scope.subject))
  }
  $scope.loadnotefromnet = function(){
    SOAP.SearchUserNote(function(res){
      if (res.getPageCount() > 0){
        $scope.netnotes = JSON.parse(r.getSearchUserNoteResult)
      } else {
        $scope.netnotes = []
      }
    },outputerrfun, $scope.subject.isubjectid, 0, 0, 10)
  }
  $scope.inputnote = {}
  $scope.addnote = function(){
    var datestr = $scope.getDate()
    $scope.subject.note = {cnotetext : $scope.inputnote.note, dchangedate: datestr}
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
        $cordovaSQLite.execute(db, 'insert into cs_writenote (isubjectid, cnotetext, dchangedate) values(?,?,?)',
          [$scope.subject.isubjectid, $scope.inputnote.note, datestr])
        .then(function(res){
        },outputerrfun)
    }
  }
  $scope.getDate = function(date){
    var d = new Date();
    var t = d.toISOString()
    return t.replace(/\..*$/, '').replace('T',' ')
  }
  $scope.gohome = function(){
    window.location.href = '#/app/home/'
  }
})

.controller("SearchCtrl", function($scope, $ionicLoading, $cordovaSQLite){

  $scope.coursename = "一级建造师"
  $scope.searchstring = {}
  $scope.search = function(){
    $scope.coursesubclasses = []
    console.log('searching' + JSON.stringify($scope.searchstring))
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
      $cordovaSQLite.execute(db, "select * from coursesubclass where csubclassname like '%" + $scope.searchstring.ccoursename + "%'", [])
      .then(function(res){
        console.log(JSON.stringify(res))
        for (var i = 0; i < res.rows.length; ++i){
          $scope.coursesubclasses.push(res.rows.item(i))
        }
      },outputerrfun)
    } else {
      for (var i = 0; i < 10; ++i){
        $scope.coursesubclasses.push({icourseid: i, isubclassid: i, csubclassname: 'testing' + i})  
      }
    }
  } 
})


.controller("SettingCtrl", function($scope, $window, $ionicModal){
  var defaultsetting = {'fontsizes' : [
    {class: 'h5', name: '小号'},
    {class: 'h4', name: '中号'},
    {class: 'h3', name: '大号'},
    {class: 'h3', name: '特大'},
    {class: 'h1', name: '超大'}], 'selectfont' : {class: 'h4', name: '中号'}, 'lighton' : false, 'evening' : false} 
  if ($window.localStorage['setting']){
    $scope.setting = JSON.parse($window.localStorage['setting'])
    console.log(JSON.stringify($scope.setting))
  } else {
    $scope.setting = defaultsetting;
    $window.localStorage['setting'] = JSON.stringify(defaultsetting)
  }
  $scope.checktoggle =function(){
    $window.localStorage['setting'] = JSON.stringify($scope.setting)
    $scope.applysetting()
  }
  $scope.reset = function(){
     $window.localStorage['setting'] = JSON.stringify(defaultsetting)
     $scope.setting = defaultsetting;
     $scope.applysetting()
  }
  $scope.select_font = function(fontconfig){
    console.log(JSON.stringify(fontconfig))
    $scope.setting['selectfont'] = fontconfig
    $window.localStorage['setting'] = JSON.stringify($scope.setting)
    if ($scope.font_modal) {$scope.font_modal.hide()}
  }
  $scope.applysetting = function(){
    $scope.setting = JSON.parse($window.localStorage['setting'])
    if ($scope.setting.lighton){
      if ($window.plugins && $window.plugins.insomnia) {$window.plugins.insomnia.keepAwake()}
    } else {
      if ($window.plugins && $window.plugins.plugins) {$window.plugins.insomnia.allowSleepAgain()}
    }
  }  
  $scope.show_select_font_modal = function(){
     if ($scope.font_modal){
      $scope.font_modal.show();
    } else {
      $ionicModal.fromTemplateUrl('templates/select_font.html', {
        scope: $scope
      }).then(function(modal){
        $scope.font_modal = modal;
        $scope.font_modal.show();
      });
    }   
  }
  $scope.close_select_font_modal = function(){
    if ($scope.font_modal){ $scope.font_modal.hide()}
  }
})

.controller("SimCtrl", function($scope, $state, $window, $stateParams, $cordovaSQLite, DB){
  $scope.courseId = parseInt($stateParams.courseId)
  console.log(JSON.stringify($stateParams))
  $scope.simulats = []
  if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
    $cordovaSQLite.execute(db, "select * from course where icourseid = ?", [$scope.courseId])
    .then(
      function(res){
        $scope.course = res.rows.item(0)
      },outputerrfun);
    $cordovaSQLite.execute(db, "select * from simulationpaper where icourseid = ?", [$scope.courseId])
    .then(function(res){
      for (var i = 0; i < res.rows.length; ++i){
        $scope.simulats.push( res.rows.item(i) )
      }
    },outputerrfun)
  } else {
    for (var i = 0; i < 2; ++i){
      $scope.simulats.push({icourseid: $scope.courseId, ipaperid: i, cpapername: '模拟考场' + i, isubjectcount: 100, itotaltime: 100, iscore: 100, dexamtime: '2015-01-0' + i})
    }
    $scope.course = DB.getcourse($scope.courseId)
  }

  $scope.create_simulation = function(){
    $state.go("create_simulation", {courseId: $scope.courseId}, {reload: true})
  }
  $scope.doRefresh = function(){
    $window.location.reload(true)
  }
})

.controller("CreateSimCtrl", function($scope,$state, $stateParams, $ionicPopup, $ionicModal, $ionicLoading, $timeout, $cordovaSQLite, DB, SIMCHAPTER){
  console.log($scope.user_partical_chapters)
  $scope.getDate = function(date){
    var d = new Date();
    var t = d.toISOString()
    return t.replace(/\..*$/, '').replace('T',' ')
  }
  $scope.courseId = parseInt($stateParams.courseId)

  $scope.sim_name = '模拟试卷' + $scope.getDate()
  $scope.total_subject = 100
  $scope.modalData = {chapters: [], select_ids: []}
  $scope.selectedchapters = []


  if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
    $cordovaSQLite.execute(db, "select * from course where icourseid = ?", [$scope.courseId])
    .then(
      function(res){
        $scope.course = res.rows.item(0)
        $scope.sim_name = $scope.course.ccoursename + ' ' + $scope.getDate()
        $cordovaSQLite.execute(db, "select * from coursechapter where icourseid = ?",[$scope.courseId])
        .then(function(cres){
          for (var i = 0; i < cres.rows.length; ++i){
            $scope.modalData.chapters.push(cres.rows.item(i))
          }
        },outputerrfun);
      },outputerrfun);
  } else {
    $scope.modalData.chapters =  DB.chapters()
    $scope.course = DB.getcourse($scope.courseId)
    $scope.sim_name = $scope.course.ccoursename + ' ' + $scope.getDate()
  }
  $scope.useallchapters =function(){
    $scope.user_partical_chapters = false

  }
  $scope.useparticalchapters = function(){
    $scope.user_partical_chapters  = true;
    if ($scope.modal){
      $scope.modal.show()
    } else {
      $ionicModal.fromTemplateUrl('templates/modal/select_sim_chapter.html', {
        scope: $scope
      }).then(function(modal) {
        $scope.modal = modal;
        $scope.modal.show()
      });
    }
  }
  $scope.closeselect = function(){
    if ($scope.modal) {
      $scope.modal.hide()
    }

    $scope.selectedchapters = []
    for (var i = 0; i < $scope.modalData.chapters.length; ++i){
      if ($scope.modalData.select_ids.indexOf($scope.modalData.chapters[i].ichapterid) >= 0){
        $scope.selectedchapters.push($scope.modalData.chapters[i])
      }
    }
  }

  $scope.create_sim = function(){
    if ($scope.user_partical_chapters && $scope.modalData.select_ids.length == 0){
       $ionicPopup.alert({title: "需要至少选择一个章节"})
       return
    }
    if ($scope.total_subject < 1){
      $ionicPopup.alert({title: "需要至少选择一道题目"})
      return 
    }
    $ionicLoading.show({template: "组卷中..."})
    $scope.subject_ids = []
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
      var query = "select isubjectid from coursesubject where isubjecttype in (0, 1) and icourseid = " + $scope.courseId
      if ($scope.user_partical_chapters){
          query = query + " and ichapterid in (" + $scope.modalData.select_ids.join() + ')'
      }
      $cordovaSQLite.execute(db, query, [])
      .then(function(res){
        var targetids = []
        for (var i = 0; i < res.rows.length; ++i) { targetids.push(res.rows.item(i).isubjectid)}
        targetids.sort(function(){return 0.5 - Math.random()}) //打乱数组
        var finalids = targetids.slice(0, $scope.total_subject)
        $cordovaSQLite.execute(db, "select count(*) as count from simulationpaper", [])
        .then(function(countres){
          var paperid =  countres.rows.item(0).count
          var datestr = $scope.getDate()
          $cordovaSQLite.execute(db, "insert into simulationpaper (ipaperid, icourseid, cpapername, itotaltime, isubjectcount, dexamtime) values(?,?,?,?,?,?)",
            [paperid, $scope.courseId, $scope.sim_name, $scope.total_subject, finalids.length, datestr]).then(function(insertres){},outputerrfun) // create simulationpaper
          $.each(finalids, function(i, subjectid){
            $cordovaSQLite.execute(db, "insert into simulationpaperdetail (ipaperid, iindex, isubjectid) values (?,?,?)",
             [paperid, i, subjectid]).then(function(insertres){
              if (i == finalids.length - 1){ 
                $ionicLoading.hide()
                $state.go("do_simulation", {paperId: paperid}, {reload: true})
                //$state.go("simulation", {courseId: $scope.courseId}, {reload: true})
          //      window.location.href = "#/simulation/" + $scope.courseId
              }
            },outputerrfun)
          }); // create simulationpaperdetail
        },outputerrfun) // select count(*)
      },outputerrfun) // select isubjectid
    } else {
      $timeout(function(){
        $ionicLoading.hide()
        $ionicPopup.alert({title: "内部错误,组卷失败"})
        $state.go("simulation", {courseId: $scope.courseId}, {reload: true})
        //window.location.href = "#/simulation/" + $scope.courseId
      }, 3000 )
    }
    
  }

  $scope.check_buy = function(chapter){
    if (chapter.ballowtest == "TRUE" || $scope.course.ihadbuy == 1){
    } else {
        $ionicPopup.confirm({
        template: '<p class="text-center">需要激活才能抽取该题目</p>',
        cancleType: 'button-positive',cancelText: '取消', okType: 'button-positive', okText: '确认'
      })
    }
  } 
  $scope.selectall = function(){
    $scope.modalData.select_ids = $scope.modalData.chapters.map(function(v){return v.ichapterid})
  }
  $scope.clearselect = function(){
    $scope.modalData.select_ids = []
  }

})


.controller("FindPassCtrl", function($scope, $ionicPopup, $ionicLoading, SOAP){
  $scope.findpassData = {}
  $scope.findpass = function(){
    $ionicLoading.show({template: '正在申请重置密码'})
    SOAP.ForgetPasswrodByEmail(function(res){
      if (res.getForgetPasswrodByEmailResult()){ 
        $ionicPopup.alert({title: "新的密码已经发送到您的邮箱中..."})
      } else {
        $ionicPopup.alert({title: "重置密码出错了..."}) 
      }
      $ionicLoading.hide()
    },function(err){
      $ionicLoading.hide()
      $ionicPopup.alert({title: "重置密码出错了..."})
    },$scope.findpassData.email)
  }
})
.controller("RegistCtrl", function($scope, $ionicPopup, $ionicLoading, $window, SOAP){
  $scope.registData = {}
  $scope.uuid = function(){
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
      return device.uuid
    } else {
      return 'webtest'
    }
  }
  $scope.doRegist = function(){
    console.log(JSON.stringify($scope.registData))
    if (!$scope.registData.email) {
        $ionicPopup.alert({title: '邮箱字段为空'})
        return
    }
    if (!$scope.registData.username) {
      $ionicPopup.alert({title: '用户名字段为空'})
      return
    }
    if (!$scope.registData.password){
      $ionicPopup.alert({title: '密码字段为空'})
      return
    }
    if (!$scope.registData.password2){
      $ionicPopup.alert({title: '确定密码字段为空'})
      return
    }
    if (!$scope.registData.phone){
      $ionicPopup.alert({title: '手机字段为空'})
      return        
    }
    if ($scope.registData.password != $scope.registData.password2){
      $ionicPopup.alert({title: '两次输入的密码不一致'})
      return
    }
    if ($scope.registData.email && $scope.registData.username && $scope.registData.password 
      && $scope.registData.phone) {
      $ionicLoading.show({template: '注册中...'})
      SOAP.CreateNewCustomer_HadQQ(function(res){
        $ionicLoading.hide()
        if (res.getCreateNewCustomer_HadQQResult() > 0){
          $ionicLoading.show({template: '注册成功, 正在跳转'})
          $window.localStorage['cusId'] = res.getCreateNewCustomer_HadQQResult()
          console.log($window.localStorage['cusId'])
          window.location.href = "#/app/info"
          $ionicLoading.hide()
        } else if (res.getCreateNewCustomer_HadQQResult() == -1){
          $ionicPopup.alert({title: '你的用户名已经被别人注册, 请重新选择一个'})
        } else if (res.getCreateNewCustomer_HadQQResult() == -2){
          $ionicPopup.alert({title: '您的邮箱已经被注册, 请重新选择一个'})
        } else if (res.getCreateNewCustomer_HadQQResult() == -3){
          $ionicPopup.alert({title: '您的手机已经被注册, 请重新选择一个'})
        } else {
         $ionicPopup.alert({title: '用户注册失败, 请过一会儿再试'})
        }

      },outputerrfun, $scope.registData.username, $scope.registData.password, $scope.registData.email, $scope.registData.phone, '', '', '', '', $scope.uuid())
    }
  }
})
.controller("LoginCtrl", function($scope, $state, $ionicPopup, $ionicLoading, $window, $ionicPlatform, SOAP, LOGOUT){
  $ionicPlatform.registerBackButtonAction(LOGOUT.logoutnotify, 100)
  $scope.loginData = {}
  if (($window.localStorage['cusId'])){
    console.log("got user id, redirect to #/app/info")
    //$state.go("app.info", {cusId: $window.localStorage['cusId']}, {reload: true})
    $state.go("app.classes", {}, {})
  }
  $scope.doLogin = function(){
    if ($scope.loginData.username && $scope.loginData.password){
      $ionicLoading.show({template: '正在登陆...'})
      SOAP.CustomerLogin(function(res){
        $ionicLoading.hide()
        if (res.getCustomerLoginResult() > 0){
          $window.localStorage['cusId'] = res.getCustomerLoginResult()
          console.log($window.localStorage['cusId'])
          console.log("using reload")
          //$state.go("app.info", {cusId: res.getCustomerLoginResult()}, { reload: true, inherit: false, notify: true })
          $state.go("app.classes", {}, {})
        } else {
          $ionicPopup.alert({title: '登陆失败, 请检查您的用户和密码'})
        }
      },function(err){
        $ionicLoading.hide()
        $ionicPopup.alert({title: '登陆失败, 网络出错了...'})
      }, $scope.loginData.username, $scope.loginData.password)
    } else {
        $ionicPopup.alert({title: '请输入用户名和密码'})
    }
  }
})

.controller("DoSimCtrl", function($scope, $stateParams, $ionicPopup, $ionicModal, $ionicLoading, $timeout, $cordovaSQLite, DB){
  console.log(JSON.stringify($stateParams))
  $scope.answerset = ['A','B','C','D','E','F','G']
  $scope.datas = [{title: 'question1'},{title: 'question12'}]
  $scope.paperId = parseInt($stateParams.paperId)
  if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android' ){
    $ionicLoading.show({template: '加载试题中...'})
    $cordovaSQLite.execute(db, "select * from simulationpaper where ipaperid = ? ", [$scope.paperId])
    .then(function(res){
      $scope.paper = res.rows.item(0)
    },outputerrfun)
    $cordovaSQLite.execute(db, "select s.isubjectid, s.icourseid, s.ichapterid, s.isubjecttype, s.ichaptertype, " + 
      "s.iscore, s.ctitle, s.cquestion, s.canswer, s.ianswercount, s.cdescription, s.bcollect, s.bcorrect, s.cmyanswer, " +
      "d.iindex from coursesubject s, simulationpaperdetail d where s.isubjectid = d.isubjectid and d.ipaperid = ?", [$scope.paperId]).then(
      function(res){
        $scope.subjects = []
        for (var i = 0; i < res.rows.length; ++i){

          var item = res.rows.item(i)
          item.iindex = i+1
          item.answerset = $scope.answerset.slice(0, item.ianswercount)
          if (item.isubjecttype == 0){
            item.single = true;
          } else {
            item.single = false;
            if(item.cmyanswer){
              item.myanswer_multi = item.cmyanswer.split('')
            } else {
              item.myanswer_multi = []
            }
          }
          if (item.cmyanswer){
            item.show_desc = true
          }
          if (item.bcollect == 'true') {
            item.src = "img/collect1.png"  
          } else {
            item.src = "img/collect0.png"
          } 
          $scope.subjects.push(item)
        }
        console.log(res.rows.length)
        $ionicLoading.hide()
        $scope.currentIndex = 0;
        $scope.subject = $scope.subjects[0];
        if (parseInt($stateParams.indexId) > 0) {
          $.each($scope.subjects, function(i, v){
            if (v.iindex == parseInt($stateParams.indexId)){
              $scope.currentIndex = i;
              $scope.subject = $scope.subjects[i];
            }
          })
        }
      },outputerrfun);//execute
  } else {
    $scope.subjects = []
    for (var i = 0; i < 200; ++i){
      if (i % 2 == 0){
        $scope.subjects.push({iindex: i, iscore: i, ctitle: '标题' + i, cdescription: '描述' + i, canswer: 'A', answerset: $scope.answerset.slice(0,4), single: true}) 
      } else {
        $scope.subjects.push({iindex: i, iscore: i, ctitle: '标题' + i,
         cdescription: '描述' + i, canswer: 'ABC', answerset: $scope.answerset.slice(0,5), single: false,
         myanswer_multi: []
       }) 
      }
    }
    $scope.currentIndex = 0;
    $scope.subject = $scope.subjects[0];
    if (parseInt($stateParams.indexId) > 0) {
      $.each($scope.subjects, function(i, v){
        if (v.iindex == parseInt($stateParams.indexId)){
          $scope.currentIndex = i;
          $scope.subject = $scope.subjects[i];
        }
      })
    }
  }
  $scope.next_subject = function(){
    if ($scope.currentIndex < $scope.subjects.length - 1){
      $scope.currentIndex++
      $scope.subject = $scope.subjects[$scope.currentIndex]
    } else {
      $scope.currentIndex=0
      $scope.subject = $scope.subjects[$scope.currentIndex]
    }
  }
  $scope.pre_subject = function(){
    if ($scope.currentIndex > 0){
      $scope.currentIndex--
      $scope.subject = $scope.subjects[$scope.currentIndex]
    } else {
      $scope.currentIndex = $scope.subjects.length - 1
      $scope.subject = $scope.subjects[$scope.currentIndex]
    }
  }
  $scope.retry_question = function(){
    $scope.subject.myanswer_single = null
    $scope.subject.myanswer_multi = []
    $scope.subject.show_desc = false
  }
  $scope.user_choose_answer_single = function(){
    $scope.subject.show_desc = true;
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
      if ($scope.subject.cmyanswer == $scope.subject.canswer){
        $scope.subject.bcorrect = 'true';
        $cordovaSQLite.execute(db, 'update coursesubject set bcorrect = ?,cmyanswer = ? where isubjectid = ?', [$scope.subject.bcorrect, $scope.subject.cmyanswer, $scope.subject.isubjectid])
      } else {
        $scope.subject.bcorrect = 'false';
        $cordovaSQLite.execute(db, 'update coursesubject set bcorrect = ?,cmyanswer = ? where isubjectid = ?', [$scope.subject.bcorrect, $scope.subject.cmyanswer, $scope.subject.isubjectid])
      }
    } else {
      $scope.subject.bcorrect = $scope.subject.cmyanswer == $scope.subject.canswer ? 'true' : 'false';
      console.log($scope.subject.cmyanswer)
    }
  }
  $scope.user_choose_answer_multi = function(){
    console.log(JSON.stringify($scope.subject.myanswer_multi))
  }


  $scope.multi_question_confirm = function(){
    $scope.subject.show_desc = true;
    $scope.subject.cmyanswer = $scope.subject.myanswer_multi.sort().join('')
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
      if ($scope.subject.cmyanswer == $scope.subject.canswer){
        $scope.subject.bcorrect = 'true';
        $cordovaSQLite.execute(db, 'update coursesubject set cmyanswer = ?, bcorrect = ? where isubjectid = ?', [$scope.subject.cmyanswer, $scope.subject.bcorrect, $scope.subject.isubjectid])
      } else {
        $scope.subject.bcorrect = 'false';
        $cordovaSQLite.execute(db, 'update coursesubject set cmyanswer = ?, bcorrect = ? where isubjectid = ?', [$scope.subject.cmyanswer, $scope.subject.bcorrect, $scope.subject.isubjectid])
      }
    } else {
     $scope.subject.bcorrect = $scope.subject.cmyanswer == $scope.subject.canswer ? 'true' : 'false';
      console.log(JSON.stringify($scope.subject.myanswer_multi))
    }
  }
  $scope.show_check_board = function(){
    $scope.groupSubjects = [];
    var groups = $scope.subjects.length / 7 + ($scope.subjects.length % 7 > 0 ? 1 : 0)
    for (var i = 0; i < groups; ++i){
      $scope.groupSubjects.push( $scope.subjects.slice(i*7, (i+1)*7) )
    }
    if ($scope.check_board){
      $scope.check_board.show();
    } else {
      $ionicModal.fromTemplateUrl('templates/modal/check_board.html', {
        scope: $scope
      }).then(function(modal){
        $scope.check_board = modal;
        $scope.check_board.show();
      });
    }
  }

  $scope.select_subject_from_board = function(s){
    $scope.submitsubject = false
    if ($scope.check_board){
      $scope.check_board.hide()
    }
    $scope.subject = s
    $scope.currentIndex = $scope.subjects.indexOf(s)
  }
  $scope.collect_subject = function(){ //收藏试题
    if ($scope.subject.bcollect == 'true') {
      $scope.subject.bcollect = 'false'
    } else {
      $scope.subject.bcollect = 'true'
    }
    if ($scope.subject.bcollect == 'true') {
      $scope.subject.src = "img/collect1.png"
    } else {
      $scope.subject.src = "img/collect0.png"
    }
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
      $cordovaSQLite.execute(db, "update coursesubject set bcollect = ? where isubjectid = ?", [$scope.subject.bcollect,$scope.subject.isubjectid])
    } else {
      console.log($scope.subject.bcollect)
    }
  }
  $scope.redoSubject = function(){
    $ionicLoading.show({template: '清空数据...'})
    $.each($scope.subjects, function(index, value){
      value.cmyanswer = null, value.bcorrect = null, value.show_desc = false, value.myanswer_multi = []
    })
    if (ionic.Platform.platform() == 'ios' || ionic.Platform.platform() == 'android'){
      $cordovaSQLite.execute(db, "update coursesubject set cmyanswer = null, bcorrect = null where ichapterid = ?", [$stateParams.chapterId]).then(
        function(res){$ionicLoading.hide()},function(err){$ionicLoading.hide()});
    } else {
      $ionicLoading.hide();
    }
    if ($scope.check_board){$scope.check_board.hide()}
  }
  $scope.calcResult = function(){
    var result = {totalAnswer: 0, rightPercent: 0, rightCount: 0,}
    $.each($scope.subjects, function(index,value){
      if (value.cmyanswer){ result.totalAnswer++ }
      if (value.bcorrect) { result.rightCount++ }
    })
    result.rightPercent = parseInt ( result.rightCount / $scope.subjects.length * 100)
    $scope.result = result;
    $scope.submitsubject = true
  }
})

.filter('answer_result', function(){
  return function(correct){
    if (correct == false){
      return  '\u2718';
    } else if (correct == true){
      return '\u2713';
    } else {
      return '\u2610';
    }
  }
})
.filter('toInt', function(){
  return function(value){ 
    if (isNaN(parseInt(value))){
      return 0
    } else {
      return parseInt(value)
    }
  }
})
  